
from util import ReadFile, WriteFile


from xyztools import extractXYZLine


def invFile(filenameIn, filenameOut):
    print " -- Checking if we need to invert?",
    # Find the amount of translation we need to do!
    data = ReadFile(filenameIn)
    dataLines = [l for l in data.split("\n") if l.strip() and not l.strip().startswith("#") ]
    CommentLines = [l for l in data.split("\n") if l.strip() and l.strip().startswith("#") ]

    
    xmin,xmax = None,None
    outData = CommentLines
    for l in dataLines:
        i,t,x,y,z,X,Y,Z,p = extractXYZLine(l)
        
        xmin = min( [xmin,x,X] ) if xmin != None else min( [x,X] )
        xmax = max( [xmax,x,X] ) if xmax != None else max( [x,X] )
        
    
    if not( xmin<=0 and xmax <=0):
        print "  No, xmin,max:", xmin,xmax 
        WriteFile(filenameOut, data)
        
    else:
        print "  Yes, xmin,max:", xmin,xmax
        # Ok, we have no positive x's:
        outData = CommentLines
        for l in dataLines:
            i,t,x,y,z,X,Y,Z,p = extractXYZLine(l)
            x = x * -1
            X = X * -1
            outData.append( "\t".join( [str(g) for g in [i,t,x,y,z,X,Y,Z,p] ] ) )
        WriteFile( filenameOut, "\n".join( outData) )
        

def nrnInvertX( srcFilename, sinkFilename):
    
    invFile(srcFilename, sinkFilename)
